import { StoreKeys } from '@/common/enum'
import { defineStore } from 'pinia'
import type { PermissionType, RoleType } from '../common/type'

// 当前用户权限
export const usePermissions = defineStore(StoreKeys.permission, {
  state: () => {
    const permissionsStr = localStorage.getItem(StoreKeys.permission)
    console.log('--permissionsStr--', permissionsStr, typeof permissionsStr)
    let def = [] as PermissionType[]
    if (permissionsStr && permissionsStr !== 'undefined') {
      def = JSON.parse(permissionsStr)
    }
    return {
      permissions: def,
    }
  },
  actions: {
    setPermissions(newList: PermissionType[]) {
      this.permissions = newList
      localStorage.setItem(
        StoreKeys.permission,
        JSON.stringify(this.permissions)
      )
    },
  },
})

// 当前用户角色
interface RoleState {
  role: RoleType | null
  roles: RoleType[]
}
export const useRole = defineStore(StoreKeys.currentRole, {
  state: (): RoleState => {
    const roleStr = localStorage.getItem(StoreKeys.currentRole)
    return {
      role: roleStr ? JSON.parse(roleStr) : {},
      roles: [],
    }
  },
  getters: {
    getRoleId: (state) => {
      return state.role?.id
    },
    getRoleName: (state) => {
      return state.role?.name
    },
    getRoleById: (state) => {
      return (roleId: number) => state.roles.find((r) => r.id === roleId)
    },
  },
  actions: {
    setRole(newRole: RoleType) {
      this.role = newRole
      localStorage.setItem(StoreKeys.currentRole, JSON.stringify(this.role))
    },
  },
})
